package controllers

import (
	"day12zz/models"
	beego "github.com/beego/beego/v2/server/web"
)

type WWW struct {
	beego.Controller
}

type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Date interface{} `json:"date"`
}

func (w *WWW) Add() {
	bao := w.GetString("bao")
	nie := w.GetString("nie")
	img := w.GetString("img")
	time := w.GetString("time")
	zuo := w.GetString("zuo")
	ww := models.Books{
		Bao:  bao,
		Nie:  nie,
		Img:  img,
		Time: time,
		Zuo:  zuo,
	}
	err := models.DB.Create(&ww).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Date: nil,
		}
		w.ServeJSON()
		return
	} else {
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Date: ww,
		}
		w.ServeJSON()
	}
}
func (w *WWW) List() {
	page, _ := w.GetInt("page", 1)
	size, _ := w.GetInt("size", 3)
	offset := (page - 1) * size
	var count int64
	var wer []models.Books
	models.DB.Table("books").Count(&count)
	err := models.DB.Offset(offset).Limit(size).Find(&wer).Error
	if err != nil {
		w.Data["json"] = Msg{
			Code: 0,
			Msg:  "分页失败",
			Date: nil,
		}
		w.ServeJSON()
		return
	} else {
		pageData := make(map[string]interface{})
		pageData["wer"] = wer
		pageData["count"] = count
		w.Data["json"] = Msg{
			Code: 200,
			Msg:  "分页成功",
			Date: pageData,
		}
		w.ServeJSON()
	}

}
